#include "bsp_gpio.h"
#include "gd32a508_gpio.h"
#include "main.h"

#define LED1_CTRL_PORT GPIOE
#define LED1_CTRL_PIN GPIO_PIN_10
#define LED2_CTRL_PORT GPIOE
#define LED2_CTRL_PIN GPIO_PIN_11
#define ON_CTRL_PORT GPIOE
#define ON_CTRL_PIN GPIO_PIN_7
#define CHG_CTRL_PORT GPIOE
#define CHG_CTRL_PIN GPIO_PIN_9
#define CC2_CTRL_PORT GPIOE
#define CC2_CTRL_PIN GPIO_PIN_8

#define TEST_SW_CTRL_PORT GPIOA
#define TEST_SW_CTRL_PIN GPIO_PIN_3


dv_DIDO_TypeDef dv_DIDO;

static void bsp_gpio_init(void)
{
	rcu_periph_clock_enable(RCU_GPIOE);

	gpio_init(LED1_CTRL_PORT, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, LED1_CTRL_PIN);
	gpio_init(LED2_CTRL_PORT, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, LED2_CTRL_PIN);
	gpio_init(ON_CTRL_PORT, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, ON_CTRL_PIN);
	gpio_init(CHG_CTRL_PORT, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, CHG_CTRL_PIN);
	gpio_init(CC2_CTRL_PORT, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, CC2_CTRL_PIN);
	
	gpio_init(TEST_SW_CTRL_PORT, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, TEST_SW_CTRL_PIN);
	
	GPIO_BC(LED2_CTRL_PORT) = LED2_CTRL_PIN;
	GPIO_BC(LED1_CTRL_PORT) = LED1_CTRL_PIN;
	GPIO_BC(ON_CTRL_PORT)   = ON_CTRL_PIN;
	GPIO_BC(CHG_CTRL_PORT)  = CHG_CTRL_PIN;
	GPIO_BC(CC2_CTRL_PORT)  = CC2_CTRL_PIN;
}

static void bsp_gpio_ctrl(GPIO_PortDef port, bool leve)
{
	switch (port)
	{
	case IO_LED1:
		(leve == true) ? (GPIO_BOP(LED1_CTRL_PORT) = LED1_CTRL_PIN) : (GPIO_BC(LED1_CTRL_PORT) = LED1_CTRL_PIN);
		break;
	case IO_LED2:
		(leve == true) ? (GPIO_BOP(LED2_CTRL_PORT) = LED2_CTRL_PIN) : (GPIO_BC(LED2_CTRL_PORT) = LED2_CTRL_PIN);
		break;
	case IO_ON:
		(leve == true) ? (GPIO_BOP(ON_CTRL_PORT) = ON_CTRL_PIN) : (GPIO_BC(ON_CTRL_PORT) = ON_CTRL_PIN);
		break;
	case IO_CHG:
		(leve == true) ? (GPIO_BOP(CHG_CTRL_PORT) = CHG_CTRL_PIN) : (GPIO_BC(CHG_CTRL_PORT) = CHG_CTRL_PIN);
		break;
	case IO_CC2:
		(leve == true) ? (GPIO_BOP(CC2_CTRL_PORT) = CC2_CTRL_PIN) : (GPIO_BC(CC2_CTRL_PORT) = CC2_CTRL_PIN);
		break;
	default:
		break;
	}
}

static bool bsp_gpio_state(GPIO_PortDef port)
{
	bool state = false;

	switch (port)
	{
		case IO_TEST_SW:
		((GPIO_ISTAT(TEST_SW_CTRL_PORT) & (TEST_SW_CTRL_PIN))) ? (state = true) : (state = false);
		break;
		default:
		break;
	}

	return state;
}

static void bsp_gpio_trigger(GPIO_PortDef port)
{
	static bool leve = false;

	switch (port)
	{
	
	default:
		break;
	}

	leve = !leve;
}

static void LED1_spark(void)
{
	if (dv_DIDO.LEDCtrl.Flag)
	{
		dv_DIDO.LEDCtrl.HCnt++;
	}
	else
	{
		dv_DIDO.LEDCtrl.LCnt++;
	}

	if (dv_DIDO.LEDCtrl.HCnt >= SYS_HEART_MS(1000))
	{
		dv_DIDO.LEDCtrl.HCnt = 0;
		dv_DIDO.LEDCtrl.Flag = false;
	}

	if (dv_DIDO.LEDCtrl.LCnt >= SYS_HEART_MS(1000))
	{
		dv_DIDO.LEDCtrl.LCnt = 0;
		dv_DIDO.LEDCtrl.Flag = true;
	}

	bsp_gpio_ctrl(IO_LED1, dv_DIDO.LEDCtrl.Flag);
}

void init_bsp_dido(void)
{
	dv_DIDO.finit     = bsp_gpio_init;
	dv_DIDO.fwrite    = bsp_gpio_ctrl;
	dv_DIDO.ftrigger  = bsp_gpio_trigger;
	dv_DIDO.fread     = bsp_gpio_state;
	dv_DIDO.fledspark = LED1_spark;
}